package com.llkj.qingnianguoxue.music;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.CourseTeacherBannerAdapter;
import com.llkj.qingnianguoxue.adapter.RecommendMusicAdapter;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.CommentResponseBean;
import com.llkj.qingnianguoxue.bean.CourseEvaluateBean;
import com.llkj.qingnianguoxue.bean.LunboBean;
import com.llkj.qingnianguoxue.bean.MusicHomeBean;
import com.llkj.qingnianguoxue.bean.RxMusicLikeBean;
import com.llkj.qingnianguoxue.home.SearchActivity;
import com.llkj.qingnianguoxue.home.SearchResultActivity;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.login.LoginActivity;
import com.llkj.qingnianguoxue.util.DisplayUtil;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.RxBus;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.llkj.qingnianguoxue.util.helper.LoadDataHelper;

import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.functions.Action1;

public class  MusicHomeActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener,
        LoadDataHelper.LoadMoreListener{
    @BindView(R.id.iv_back)
    protected ImageView ivBack;
    @BindView(R.id.tv_search)
    protected TextView tvSearch;//搜索
    @BindView(R.id.et_search)
    protected EditText etSearch;
    @BindView(R.id.ssw_banner)
    protected ConvenientBanner ssvBanner;//轮播图
    @BindView(R.id.llMusicLike)
    protected LinearLayout llMusicLike;
    @BindView(R.id.llMusicAll)
    protected LinearLayout llMusicAll;
    @BindView(R.id.llMusicMine)
    protected LinearLayout llMusicMine;
    @BindView(R.id.recyclerView)
    protected RecyclerView rlMusic;
    private RecommendMusicAdapter mMusicAdapter;
    private List<CourseEvaluateBean> mMusicData;
    private int mPage = 1,mCurrentPosition;//分页，当前位置
    private int totalSize;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_home);
        ButterKnife.bind(this);

        initData();

        mPage = 1;
        loadWaitDialog();
        getData();
    }

    private void initData(){
        RelativeLayout rlTop = findViewById(R.id.rl_top);
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,rlTop,R.color.gray_bar);
        ssvBanner.getLayoutParams().height = DisplayUtil.getDensityWdith(this)*9/16;
        rlMusic.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,false));
        mMusicData = new ArrayList<>();
        mMusicAdapter = new RecommendMusicAdapter(R.layout.item_recommend_music,mMusicData);
        rlMusic.setAdapter(mMusicAdapter);

        rlMusic.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
                if (!isLogin) {
                    dialogConfirm(null, null, null, null).show();
                    return;
                }
                mCurrentPosition = i;
                CourseEvaluateBean item = mMusicData.get(mCurrentPosition);
                if(view.getId()== R.id.btnSing){//演唱
                    RecordMusicActivity.startActivity(MusicHomeActivity.this,item.getId(),item.getSing_img()
                            ,item.getName(),item.getPlay_num(),item.getAccompaniment(),item.getMp3(),item.getLyric(),item.getSing_name());
                }else if(view.getId() == R.id.ivPraise){//喜欢
//                    loadWaitDialog();
                    String type = "1".equals(item.getIs_like())?"2":"1";
                    HttpMethod.kojiUserOperation(MusicHomeActivity.this,MusicHomeActivity.this,item.getId(),type,"2");
                }
            }
        });
        rlMusic.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                mCurrentPosition = i;
                CourseEvaluateBean item = mMusicData.get(i);
                Bundle bundle  = new Bundle();
                bundle.putString("musicId",item.getId());
                startActivity(MusicDetailActivity.class,bundle);
            }
        });
        mMusicAdapter.setOnLoadMoreListener(this);
        RxBus.getInstance().toObservable(RxMusicLikeBean.class).subscribe(new Action1<RxMusicLikeBean>() {
            @Override
            public void call(RxMusicLikeBean s) {
                CourseEvaluateBean item = mMusicData.get(mCurrentPosition);
                String isLike = s.isCheck?"1":"2";
                item.setIs_like(isLike);
                mMusicAdapter.notifyItemChanged(mCurrentPosition);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        ssvBanner.startTurning(5000);
    }

    @Override
    public void onPause() {
        super.onPause();
        ssvBanner.stopTurning();
    }

    @Override
    protected void dialogRightBtn() {
        super.dialogRightBtn();
        startActivity(LoginActivity.class);
    }

    /**
     * 轮播图
     *
     * @param list_image
     */
    private void initBanner(final List<LunboBean> list_image) {
        if (list_image == null) {
            return;
        }
        final CourseTeacherBannerAdapter bannerAdapter = new CourseTeacherBannerAdapter(new CourseTeacherBannerAdapter.ClickBannerListener() {

            @Override
            public void clickBanner(int position) {
                LunboBean lunboBean = list_image.get(position);
                Bundle bundle  = new Bundle();
                bundle.putString("musicId",lunboBean.getContent_id());
                startActivity(MusicDetailActivity.class,bundle);
            }
        });

        ssvBanner.setPages(new CBViewHolderCreator<CourseTeacherBannerAdapter>() {
            @Override
            public CourseTeacherBannerAdapter createHolder() {
                return bannerAdapter;
            }
        }, list_image);

    }

    @OnClick({R.id.iv_back, R.id.tv_search, R.id.llMusicLike, R.id.llMusicAll, R.id.llMusicMine})
    public void onClick(View view){
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        switch (view.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_search:
                String searchWord = etSearch.getText().toString();
                if(StringUtils.isEmpty(searchWord)){
                    ToastUtil.makeLongText(this,"请输入搜索内容");
                    return;
                }
                Intent intent = new Intent(this, SearchResultActivity.class);
                intent.putExtra("searchWord",searchWord);
                intent.putExtra("searchCategory","musicSearch");
                startActivity(intent);
                break;
            case R.id.llMusicLike://喜欢
                if (!isLogin) {
                    dialogConfirm(null, null, null, null).show();
                    return;
                }
                startActivity(MusicLikeActivity.class);
                break;
            case R.id.llMusicAll://全部
                startActivity(MusicAllActivity.class);
                break;
            case R.id.llMusicMine://我唱的
                if (!isLogin) {
                    dialogConfirm(null, null, null, null).show();
                    return;
                }
                startActivity(MusicMineActivity.class);
                break;
        }
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
//        refreshLayout.setRefreshing(false);
        if (HttpMethod.HTTP_KOJI_INDEX == method) {//2.1首页
            MusicHomeBean homeBean = GsonUtil.GsonToBean(data,MusicHomeBean.class);
            if(homeBean!=null){
                try{
                    totalSize = Integer.parseInt(homeBean.getNum());
                }catch (Exception e){}

                if(homeBean.getCarousel()!=null && homeBean.getCarousel().size()>0){
                    initBanner(homeBean.getCarousel());
                }
                if (mPage == 1) {
                    mMusicData.clear();
                    LoadDataHelper.refreshComplete(mMusicAdapter, mMusicData, null, rlMusic);
                } else {
                    mMusicAdapter.setEnableLoadMore(true);
                    mMusicAdapter.loadMoreComplete();
                }
                if(homeBean.getKoji()!=null){
                    mMusicData.addAll(homeBean.getKoji());
                    mMusicAdapter.notifyDataSetChanged();
                }
            }
        }else if(HttpMethod.HTTP_KOJI_USER_OPERATION == method){
            CourseEvaluateBean item = mMusicData.get(mCurrentPosition);
            String type = "1".equals(item.getIs_like())?"2":"1";
            item.setIs_like(type);
            mMusicAdapter.notifyItemChanged(mCurrentPosition);
        }
    }

    @Override
    public void onLoadMore() {
        mPage++;
        getData();
    }

    private void getData(){
        HttpMethod.kojiIndex(this,this,String.valueOf(mPage));
    }

    @Override
    public void onLoadMoreRequested() {
        LoadDataHelper.loadMoreRequest(this, mMusicAdapter, null, rlMusic, totalSize);
    }
}
